package com.tmp.util;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

public class VelocityUtil {

	private final static VelocityEngine velocity = new VelocityEngine();

	static {
		try {
			InputStream propIs = VelocityUtil.class.getClassLoader().getResourceAsStream("velocity.properties");
			Properties velocityProperties = new Properties();
			velocityProperties.load(propIs);
			velocity.init(velocityProperties);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param vmpath
	 *            vm文件路径
	 * @param ctxMap
	 * @return
	 */
	public static String getContent(String vmpath, Map<String, Object> ctxMap) {
		if (StringUtils.isEmpty(vmpath)) {
			return null;
		}
		VelocityContext ctx = new VelocityContext(ctxMap);
		Template template = null;
		try {
			// 此处需要指定编码，如不指定中文有可能是乱码
			// template = velocity.getTemplate(vmpath, "UTF-8");

			template = velocity.getTemplate(vmpath);
			if (template == null) {
				return null;
			}
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			// 此处需要指定编码，如不指定中文有可能是乱码
			Writer writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
			template.merge(ctx, writer);
			writer.flush();
			writer.close();
			return new String(os.toByteArray());
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("============ main ==========");
	}

}
